package leetcode.medium;

/**
 * Created by hasee on 2017/5/24.
 * Given two strings representing two complex numbers.

 You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
 */
public class ComplexNumberMultiplication_537 {

    public static String complexNumberMultiply(String a, String b) {
        StringBuilder result = new StringBuilder();
        String[] as = a.replaceAll("i","").split("\\+");
        String[] bs = b.replaceAll("i","").split("\\+");
        int front = Integer.parseInt(as[0]) * Integer.parseInt(bs[0]);
        int medium =Integer.parseInt(as[0])*Integer.parseInt(bs[1])+Integer.parseInt(as[1])*Integer.parseInt(bs[0]);
        int back = Integer.parseInt(as[1])*Integer.parseInt(bs[1])*(-1);
        return result.append((front+back)).append("+").append(medium).append("i").toString();
    }
    public static void main(String[] args){
        System.out.println(bestAnswer("1+-1i","1+-1i"));
    }

    public static String bestAnswer(String a, String b) {
        int[] aa=getN(a.toCharArray());
        int[] bb=getN(b.toCharArray());
        int Re=aa[0]*bb[0]-aa[1]*bb[1];
        int Im=aa[0]*bb[1]+aa[1]*bb[0];
        return ""+Re+"+"+Im+"i";
    }
    public static int[] getN(char[] str){
        int[] ret=new int[2];
        ret[0]=ret[1]=0;
        int flag=1;
        int index=0;
        if(str[index]=='-'){
            flag=-1;
            index++;
        }
        for(;str[index]!='+';index++){
            ret[0]=ret[0]*10+str[index]-'0';
        }
        ret[0]*=flag;
        index++;
        flag=1;
        if(str[index]=='-'){
            flag=-1;
            index++;
        }
        for(;str[index]!='i';index++){
            ret[1]=ret[1]*10+str[index]-'0';
        }
        ret[1]*=flag;
        return ret;
    }
}
